package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstants;
import com.zzyl.dto.LoginDto;
import com.zzyl.entity.Resource;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.properties.SecurityConfigProperties;
import com.zzyl.service.LoginService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.UserAuth;
import com.zzyl.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private SecurityConfigProperties securityConfigProperties;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 用户登录
     * @param loginDto
     * @return
     */
    @Override
    public UserVo login(LoginDto loginDto) {
        //调用认证管理器，让框架帮你查询校验用户
        UsernamePasswordAuthenticationToken upat =
                new UsernamePasswordAuthenticationToken(loginDto.getUsername(),loginDto.getPassword());
        Authentication authenticate = authenticationManager.authenticate(upat);
        //是否认证成功
        if(!authenticate.isAuthenticated()){
            throw new RuntimeException("用户登录失败");
        }
        //获取用户对象
        UserAuth principal = (UserAuth) authenticate.getPrincipal();
        //对象转换
        UserVo userVo = BeanUtil.toBean(principal, UserVo.class);

        //过滤敏感数据
        userVo.setPassword("");

        //获取当前用户对应的资源列表
        List<Resource> resourceList = resourceMapper.selectByUserId(userVo.getId());
        //取出request_path
        List<String> urlList = resourceList.stream().map(Resource::getRequestPath).collect(Collectors.toList());

        //获取白名单url列表
        List<String> publicAccessUrls = securityConfigProperties.getPublicAccessUrls();
        urlList.addAll(publicAccessUrls);

        //生成token

        //把数据存入map
        Map<String,Object> claims = new HashMap<>();
        claims.put("currentUser", JSONUtil.toJsonStr(userVo));
        //创建token
        String token = JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey()
                , jwtTokenManagerProperties.getTtl(), claims);
        //过期时间
        int ttl = jwtTokenManagerProperties.getTtl() /1000;

        //存储到redis
        redisTemplate.opsForValue().set(CacheConstants.PUBLIC_ACCESS_URLS +userVo.getId(),JSONUtil.toJsonStr(urlList),
        ttl, TimeUnit.SECONDS);

        userVo.setUserToken(token);

        return userVo;
    }
}
